package ltd.rycloud.tms.controller;



import ltd.rycloud.tms.entity.Businesstrip;
import ltd.rycloud.tms.entity.Submit;
import ltd.rycloud.tms.entity.Traininfo;
import ltd.rycloud.tms.entity.User;
import ltd.rycloud.tms.service.BusinesstripService;
import ltd.rycloud.tms.service.SubmitService;
import ltd.rycloud.tms.service.TrainService;
import ltd.rycloud.tms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by wowx on 12/10/2018.
 */
@Controller
public class UserManagerController {
    @Autowired
    UserService userService;
    @Autowired
    TrainService trainService;
    @Autowired
    BusinesstripService businesstripService;
    @Autowired
    SubmitService submitService;
    @GetMapping("/userList")
    public String userList(Model model) {
        List<User> users = userService.findAll();
        model.addAttribute("users", users);
        return "/usermanager/userlist";
    }

    @GetMapping("/userpage")
    public String userPage() {
        return "/usermanager/useradd";
    }

    @PostMapping("/useradd")
    public String userAdd(User user, Model model) {
      //  user.setLastlogindate(new Date());
        userService.save(user);
        model.addAttribute("msg", "追加用户成功");
        return "/message";
    }

    @GetMapping("/userdel/{id}")
    public String userDel(@PathVariable("id") int id, Model model) {
        userService.delete(id);
        model.addAttribute("msg", "删除用户成功");
        return "/message";
    }
    @GetMapping("/traindel/{id}")
    public String train(@PathVariable("id") int id,Model model){
        trainService.delete(id);
        model.addAttribute("msg","培训信息删除成功!");
        return "/message";
    }

    @GetMapping("/usereditpage/{id}")
    public String userEditPage(@PathVariable("id") int id, Model model) {
        User user = userService.getUser(id);
        model.addAttribute("user", user);
        return "/usermanager/useredit";
    }
    @GetMapping("trainsInfoEdit/{id}")
    public String trainsInfoEdit(@PathVariable("id") int id,Model model){
        Traininfo train = trainService.getTrain(id);
        model.addAttribute("train",train);
        return "work/trainsInfoEdit";
    }
    @PostMapping("trainedit")
    public String trainedit(Model model,Traininfo train){
        System.out.println(train.getContent()+train.getTitle()+train.getUserId());
        trainService.save(train);
        model.addAttribute("msg","培训信息更新成功");
        return "message";
    }

    @PostMapping("/useredit")
    public String userEdit(User user, Model model) {
        userService.edit(user);
        model.addAttribute("msg", "编辑成功");
        return "/message";
    }

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //转换日期
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
    }

    @InitBinder
    public void initBinder01(WebDataBinder binder, WebRequest request) {
        //转换日期
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
    }

    @GetMapping("/modifyPwd")
    public String modifyPwd() {
        return "/usermanager/modifyPwd";
    }

    @PostMapping("modifyPwd01")
    public String modifyPwd01(User user, Model model, HttpSession session) {
        User user01 = (User) session.getAttribute("loadsession");
        user01.setPassword(user.getPassword());
       // user01.setLastlogindate(new Date());
        if (!(user01.getLastpsd().equals(user.getLastpsd()))) {
            model.addAttribute("msg", "请输入正确的旧密码！");
            System.out.println(user.getLastpsd() + user01.getLastpsd());
            return "/message";
        }
        user01.setLastpsd(user.getPassword());
        userService.save(user01);
        model.addAttribute("msg", "密码修改成功！");
        return "/message";
    }

    @GetMapping(value = {"load"})
    public String load() {
        return "/usermanager/load";
    }

    @GetMapping("/register")
    public String register() {
        //List<User> users=userService.findAll();
        return "/usermanager/register";
    }

    @PostMapping("/judgeType")
    public String judgeType(User user, Model model, HttpSession session) {
        User user1 = userService.login(user.getUsername(), user.getPassword());
        model.addAttribute("loaduser", user1);
        session.setAttribute("loadsession", user1);
        //System.out.println("输出的是USER信息："+user1.getRegistrationdate());//此处测试user信息是否查询出来
        //model.addAttribute("users",users);
        if (user1 != null)
            switch (user1.getType()) {
                case 1:
                {
                    List<Traininfo> trains = trainService.findAll();
                    model.addAttribute("trains",trains);
                    return "/work/trainInfoBrowse";//此处跳转培训信息浏览页面
                     }
                case 2:
                    return "work/leader";
                case 3:
                    return "work/secretary";
                case 4:
                    return "/usermanager/load";
            }
        return "/index";
    }

    @PostMapping("/register")
    public String register(User user, Model model) {

       // user.setRegistrationdate(new Date());
      //  user.setLastlogindate(new Date());
        userService.save(user);
        model.addAttribute("msg", "注册成功");
        return "/index";
    }

    @GetMapping("/shouye")
    public String shouYe(HttpSession session,Model model) {
        User user = (User) session.getAttribute("loadsession");
        if ((user.getType() == 1) || (user.getType() == 2) || (user.getType() == 3) || (user.getType() == 4)) {
            switch (user.getType()) {
                case 1:
                    List<Traininfo> trains = trainService.findAll();
                    model.addAttribute("trains",trains);
                    return "/work/trainInfoBrowse";//此处跳转培训信息浏览页面
                case 2:
                    return "work/leader";
                case 3:
                    return "work/secretary";
                case 4:
                    return "/usermanager/load";
            }
        }
        return "#";
    }
    @PostMapping("/createTrainInfo")
    public String createTrainInfo(Traininfo train,Model model){
        if (train.getTitle()==""){
            model.addAttribute("msg","培训信息信息发布失败-无标题信息");
            return "/message";
        }
        System.out.println("得到的信息为："+train.getTitle());
        trainService.save(train);//此处会报错！错误为空指针异常，尚未解决问题 2018.12.24 0：02    此问题已解决 原因是 所在controller中引入service时候，service上面忘记写@Resource或者@Autowired注解导致的
        model.addAttribute("msg","培训信息信息发布成功");
     return "/message";
    }
    @GetMapping("gotocreateTrainInfo")
    public String gotocreateTrainInfo(){
        return "/work/createTrainInfo";
    }
    @GetMapping("/trainInfoBrowse")
    public String trainInfoBrowse(Model model){

        List<Traininfo> trains = trainService.findAll();
        model.addAttribute("trains",trains);
        return "/work/trainInfoBrowse";//此处跳转培训信息浏览页面
    }
    //头像文件上传
//    @RequestMapping("/uploadhead")
//    public String uploadhead(@RequestParam("headImage") MultipartFile file, int id, HttpServletRequest req) {
//
//        if (file.isEmpty()) {
//            return "上传失败，请选择文件";
//        }
//        //获取tomcat相对路径
//        String path = req.getServletContext().getRealPath("/");
//        //获取上传文件的名字
//        String fileName = file.getOriginalFilename();
//        Date date=new Date();
//        //获取当前系统时间戳
//        long time=date.getTime();
//        //用IMG+时间戳来对上传文件进行命名  防止重名   (获取文件的后缀名)
//        String name="IMG_"+time+"."+fileName.substring(fileName.lastIndexOf(".")+1);
//        //文件保存路径
//        System.out.print("路径" + path+"/"+name);
//
//
//        //String filePath = "d:/webtest/";
//        File dest = new File(path + name);
//        try {
//            file.transferTo(dest);
//            Resume Jianli = new Resume();
//            Jianli.setId(id);
//            Jianli.setHeadimage("/"+name);
//            jianliService.inset(Jianli);
//            return "redirect:/chaxun?id="+id;
//        } catch (IOException e) {
//
//        }
//        return "redirect:/chaxun?id="+id;
//    }
    @GetMapping("Applybusinesstrip")
    public String applybusinesstrip(){
        return "work/applybusiness";
    }
    @PostMapping("saveapply")
    public String saveapply(Model model, Businesstrip businesstrip){
        System.out.println(businesstrip.getStartdate()+"******"+businesstrip.getEnddate());
        businesstripService.save(businesstrip);
        model.addAttribute("msg","申请已提交，请等待审核");
        return "message";
    }
    @GetMapping("Applysubmit")
    public String applysubmit(){
        return "work/applysubmit";
    }
    @PostMapping("savesubmit")
    public String savesubmit(Model model, Submit submit){

        submitService.save(submit);
        model.addAttribute("msg","申请已提交，请等待审核");
        return "message";
    }
    @GetMapping("findbuspage")
    public String findbus(Model model){

        List<Businesstrip> businesstrips = businesstripService.findAll();
        model.addAttribute("buss",businesstrips);
        return "work/findbus";
    }
    @GetMapping("toleaderfindbus")
    public String toleaderfindbus(Model model){
        List<Businesstrip> businesstrips = businesstripService.findAll();
        model.addAttribute("buss",businesstrips);
        return "/work/Leaderfindbus";
    }
    @GetMapping("toleaderfindsub")
    public String toleaderfindsub(Model model){
        List<Submit> su = submitService.findAll();
        model.addAttribute("buss",su);
        return "/work/Leaderfindsub";
    }
    @GetMapping("tomishubus")
    public String toMishuBus(Model model){
        List<Businesstrip> businesstrips = businesstripService.findAll();
        model.addAttribute("buss",businesstrips);
        return "work/mishufindbus";
    }

    @GetMapping("findApplysubmit")
    public String findApplysubmit(Model model){

        List<Submit> businesstrips = submitService.findAll();
        model.addAttribute("buss",businesstrips);
        return "work/findsub";
    }
    @GetMapping("toleadersub")
    public String toleadersub(Model model){

        List<Submit> businesstrips = submitService.findAll();
        model.addAttribute("buss",businesstrips);
        return "work/Leaderfindsub";
    }
}




